import asyncio
import datetime
import uvicorn

from fastapi import FastAPI

# import apscheduer
from apscheduler.schedulers.asyncio import AsyncIOScheduler


app = FastAPI(title='fast-api')


scheduler = None


@app.on_event('startup')
def init_scheduler():
    """初始化"""
    global scheduler
    scheduler = AsyncIOScheduler()
    scheduler.configure()
    # 添加一个coroutine执行，结果很不理想...
    print("启动调度器...")
    scheduler.start()
    scheduler.add_job(tick, 'interval', seconds=3)


def print_time(name):
    print(f'{name} - {datetime.datetime.now()}')


async def tick():
    print('Tick! The time is: %s' % datetime.datetime.now())
    await asyncio.sleep(1)


@app.get('/add-job')
async def add_job(job_id: str):
    """添加job"""
    scheduler.add_job(id=job_id, func=print_time, args=(
        job_id), trigger='interval', seconds=2)
    return {"msg": "success!"}


@app.get('/remove-job')
async def remove_job(job_id: str):
    """移除job"""
    scheduler.remove_job(job_id)
    return {"msg": "success!"}


if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=5566)
